package com.ken.astroboy.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.quartz.CronExpression;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;

public class GetExecuteTimeForCronExpression {

	public static String convert(String cronExpression) throws ParseException
	{    
        StringBuilder sb = new StringBuilder();

		try {
			CronExpression exp = new CronExpression(cronExpression);
			Date d = new Date();
			d = exp.getNextValidTimeAfter(d); 
		} catch (ParseException e1) {
			sb.append(("运行时间Cron格式错误\r\n"));
			return sb.toString();
		} 
		
	    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
        cronTriggerImpl.setCronExpression(cronExpression);
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        
        int duration = 3;
        calendar.add(Calendar.MONTH, duration);
        List<Date> dates = TriggerUtils.computeFireTimesBetween(
                cronTriggerImpl, null, now, calendar.getTime());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
                
        sb.append("采用Cron表达式：[")
          .append(cronExpression)
          .append("] 的任务在最近")
          .append(Integer.toString(duration))
          .append("个月内将会执行")
          .append(Integer.toString(dates.size()))
          .append("次, 分别是：\r\n\r\n");
        
        for (int i = 0; i < dates.size(); i++) {
            if (i == 50) {
            	sb.append("...");
                break;
            }
            sb.append(dateFormat.format(dates.get(i)))
              .append("\r\n");
        }
        
		return sb.toString();
	}	
}
